package com.gm.wholesale.module.order.view.orderManger;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.http.SslError;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.interfaces.IResultListener;
import com.gm.commonlib.module.image.ImageUtil;
import com.gm.commonlib.module.image.takeimage.ShowBigImagePopWindow;
import com.gm.commonlib.module.print.PrintUtil;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.listviews.MyListView;
import com.gm.commonlib.views.superview.SuperTextView;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.BuildConfig;
import com.gm.wholesale.R;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderChangeBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderDetailBean;
import com.gm.wholesale.module.order.model.NeedOrderModel;
import com.gm.wholesale.module.order.orderStatus.NeedOrderStatusType;
import com.gm.wholesale.module.order.orderStatus.OrderChangeType;
import com.gm.wholesale.module.order.ui.OrderMangerFragment;
import com.gm.wholesale.module.order.ui.needOrder.ReceiptActivity;
import com.gm.wholesale.module.user.UserDataManger;
import com.gm.wholesale.util.ViewUtil;

import java.util.List;

/**
 * 需求單詳情
 */
public class NeedOrderDetailView extends LinearLayout {
    private TextView orderTitleTv;
    private TextView orderNumTv;
    private TextView createOrderTimeTv;
    private TextView sendOrderTimeTv;
    private TextView remarkTv;
    private LinearLayout imageLinView;
    private SuperTextView printTv;
    private SuperTextView LeftFunctionTv;
    private SuperTextView knowChangeTextView;

    private MyListView myListView;

    private TextView moneyTv;
    private View rightView;
    private Context context;

    private NeedOrderBean mNeedOrderBean;

    private NeedOrderDetailBean mOrderDetail;

    private View lineView;
    private ImageView receiptImage1;
    private ImageView receiptImage2;
    private ImageView receiptImage3;
    private ImageView receiptImage4;

    private WebView mWebView;

    private OrderMangerFragment mOrderMangerFragment;
    private boolean mIsLoadSuccess;

    public void setOrderMangerFragment(OrderMangerFragment fragment) {
        mOrderMangerFragment = fragment;
    }


    public void showView() {
        //todo 有数据才显示
        if (this.mOrderDetail != null) {
            setVisibility(VISIBLE);
        }
    }

    public NeedOrderDetailView(Context context) {
        super(context);
        initView(context);
    }

    public NeedOrderDetailView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.view_need_order_detail, this);
        LeftFunctionTv = findViewById(R.id.leftTv);
        mWebView = findViewById(R.id.webView);
        ViewUtil.initWebView(mWebView);
        orderTitleTv = findViewById(R.id.orderTitleTv);
        orderNumTv = findViewById(R.id.orderNumTv);
        createOrderTimeTv = findViewById(R.id.createOrderTimeTv);
        sendOrderTimeTv = findViewById(R.id.sendOrderTimeTv);
        remarkTv = findViewById(R.id.remarkTv);
        imageLinView = findViewById(R.id.imageLinView);
        printTv = findViewById(R.id.printTv);
        myListView = findViewById(R.id.wordListView);
        knowChangeTextView = findViewById(R.id.knowChangeTv);
        lineView = findViewById(R.id.lineView);
        receiptImage1 = findViewById(R.id.receiptImage1);
        receiptImage2 = findViewById(R.id.receiptImage2);
        receiptImage3 = findViewById(R.id.receiptImage3);
        receiptImage4 = findViewById(R.id.receiptImage4);
        moneyTv = findViewById(R.id.moneyTv);
        rightView = findViewById(R.id.rightView);
        knowChangeTextView.setOnClickListener(v -> {
            if (RepeatClickUtils.check()) return;
            if (mOrderDetail != null) {
                NeedOrderModel.knowOrder(mOrderDetail.getNeedsID(), mOrderDetail.getVersion(), (IBaseView) context, new BaseHttpObserver<BaseResp>() {
                    @Override
                    protected void handleResultOkResp(BaseResp resp) {
                        //修改状态为已接单
                        mNeedOrderBean.setChanged(false);
                        EvenBusUtil.updateNeedOrderListItem(mNeedOrderBean);
                        showView(mNeedOrderBean);
                    }
                });
            }

        });
        printTv.setOnClickListener(v -> {
            if (RepeatClickUtils.check() || mNeedOrderBean == null) return;
            print();

        });

    }

    public void loadUrl(long id) {
        String url = BuildConfig.WEB_HOST + "order_receive_print?needsId=" + id + "&token=" + UserDataManger.newInstance().getToken();
        mWebView.loadUrl(url);
        mWebView.setWebViewClient(new WebViewClient() {
                                      @Override
                                      public void onPageFinished(WebView view, String url) {
                                          super.onPageFinished(view, url);
                                          mIsLoadSuccess = true;
                                      }

                                      @Override
                                      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                          super.onReceivedError(view, errorCode, description, failingUrl);
                                          ToastUtil.showToast(description);
                                          mIsLoadSuccess = false;
                                      }

                                      @Override
                                      public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                          view.loadUrl(url);
                                          return false;

                                      }

                                      @Override
                                      public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                          handler.proceed();
                                          super.onReceivedSslError(view, handler, error);
                                      }

                                      @Override
                                      public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                                          super.onReceivedHttpError(view, request, errorResponse);
                                          mIsLoadSuccess = false;
                                      }

                                  }


        );
    }

    public void updateOrderState() {
        if (mNeedOrderBean == null) return;
        //未打印的才去改变状态
        if (mNeedOrderBean.getStatus() == NeedOrderStatusType.DJD.getType()) {//显示截单按钮
            acceptOrder();
        }
    }




    public void showView(NeedOrderBean needOrderBean) {
        if (needOrderBean==null)return;
        loadUrl(needOrderBean.getNeedsId());
        setVisibility(VISIBLE);
        knowChangeTextView.setVisibility(GONE);
        this.mNeedOrderBean = needOrderBean;
        getOrderDetail(needOrderBean.getNeedsId(), null);


    }

    private void getOrderDetail(long id, IResultListener<NeedOrderDetailBean> iResultListener) {
        NeedOrderModel.getNeedOrderDetail(id,  null, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<NeedOrderDetailBean> resp) {
                if (resp == null) return;
                mOrderDetail = resp.getData();
                //todo 有变更才去 获取变更记录,不然直接显示
                if (mNeedOrderBean.isChanged()) {
                    getOrderChangeData(resp.getData(), id, iResultListener);
                } else {
                    showView(mOrderDetail);
                    if (iResultListener != null) {
                        iResultListener.onResult(mOrderDetail);
                    }
                }

            }
        });
    }


    private void getOrderChangeData(NeedOrderDetailBean data, long id, IResultListener<NeedOrderDetailBean> iResultListener) {
        NeedOrderModel.getOrderChangeInfo(id, null, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<NeedOrderChangeBean> resp) {
                if (resp != null) {
                    knowChangeTextView.setVisibility(VISIBLE);
                    NeedOrderChangeBean changeBean = resp.getData();
                    if (changeBean != null) {
                        data.setChangeImages(changeBean.getImages());
                        data.setChangeTexts(changeBean.getTexts());
                    }
                } else {
                    knowChangeTextView.setVisibility(GONE);
                }

            }

            @Override
            protected void handleResultOtherResp(DataResp<NeedOrderChangeBean> resp) {
                knowChangeTextView.setVisibility(GONE);
            }

            @Override
            public void onComplete() {
                showView(data);
                if (iResultListener != null) {
                    iResultListener.onResult(data);
                }

            }
        });
    }

    private void showView(NeedOrderDetailBean detailBean) {
        if (detailBean == null) return;
        showFunctionBtn(detailBean);
        //订单基础信息
        showOrderBaseInfo(detailBean);
        showImages(detailBean);
        //订单详情商品信息
        showOrderGoodInfo(detailBean);
        //回执信息
        showReceiptView(detailBean);

    }

    private void hidReceiptView() {
        lineView.setVisibility(GONE);
        rightView.setVisibility(GONE);
    }

    private void showReceiptView() {
        lineView.setVisibility(VISIBLE);
        rightView.setVisibility(VISIBLE);
    }

    //回执信息
    private void showReceiptView(NeedOrderDetailBean data) {
        receiptImage1.setImageResource(0);
        receiptImage2.setImageResource(0);
        receiptImage3.setImageResource(0);
        receiptImage4.setImageResource(0);
        //todo 没有回执不显示
        if (data.getStatus() != NeedOrderStatusType.YWC.getType()) {
            hidReceiptView();
            return;
        }

        NeedOrderDetailBean.ReceiptBean receiptBean = data.getReceipt();
        if (receiptBean == null) {
            hidReceiptView();
            return;
        }
        List<String> images = receiptBean.getImages();
        String amount = receiptBean.getAmount();

        if (images == null && TextUtils.isEmpty(amount)) {
            hidReceiptView();
            return;
        }
        showReceiptView();
        if (receiptBean != null) {
            moneyTv.setText("记账: " + NumberUtils.getMoneyString(receiptBean.getAmount()));
        }
        if (images != null && !images.isEmpty()) {
            switch (images.size()) {
                case 1:
                    showImage(images.get(0), receiptImage1);
                    break;
                case 2:
                    showImage(images.get(0), receiptImage1);
                    showImage(images.get(1), receiptImage2);
                    break;
                case 3:
                    showImage(images.get(0), receiptImage1);
                    showImage(images.get(1), receiptImage2);
                    showImage(images.get(2), receiptImage3);
                    break;
                case 4:
                    showImage(images.get(0), receiptImage1);
                    showImage(images.get(1), receiptImage2);
                    showImage(images.get(2), receiptImage3);
                    showImage(images.get(3), receiptImage4);
                    break;
            }
        }


    }

    private void showImage(String path, ImageView imageView) {
        if (path == null) return;
        ImageUtil.showImage(imageView, path);
        String finalPath = path;
        imageView.setOnClickListener(v -> {
            ShowBigImagePopWindow showBigImagePopWindow = new ShowBigImagePopWindow(context);
            showBigImagePopWindow.showImage(finalPath, v);
        });
    }

    private void showFunctionBtn(NeedOrderDetailBean orderDetail) {
        printTv.setVisibility(VISIBLE);
        if (orderDetail == null) return;
        int status = orderDetail.getStatus();
        LeftFunctionTv.setVisibility(VISIBLE);
        if (status == NeedOrderStatusType.DJD.getType()) {
            LeftFunctionTv.setVisibility(GONE);
        } else if (status == NeedOrderStatusType.YJD.getType()) {
            LeftFunctionTv.setCenterString("截单");
            LeftFunctionTv.setOnClickListener(v -> {
                if (RepeatClickUtils.check()) return;
                if (orderDetail == null) return;
                finishOrder(orderDetail);
            });
        } else {
            LeftFunctionTv.setCenterString("回执");
            LeftFunctionTv.setOnClickListener(v -> {
                if (RepeatClickUtils.check()) return;
                startReceiptAct(orderDetail);
            });
        }
    }

    //打印|接单
    private void acceptOrder() {
        if (mOrderDetail == null) return;
        NeedOrderModel.acceptOrder(mOrderDetail.getNeedsID(), mOrderDetail.getVersion(), null, new BaseHttpObserver<BaseResp>() {
            @Override
            protected void handleResultOkResp(BaseResp resp) {
                //修改状态为已接单
                mNeedOrderBean.setStatus(NeedOrderStatusType.YJD.getType());
                EvenBusUtil.updateNeedOrderListItem(mNeedOrderBean);
                getOrderDetail(mOrderDetail.getNeedsID(), null);
            }
        });
    }

    //截单
    private void finishOrder(NeedOrderDetailBean orderDetailBean) {
        if (mOrderDetail == null) return;
        NeedOrderModel.finishNeedOrder(orderDetailBean.getNeedsID(), orderDetailBean.getVersion(), (IBaseView) context, new BaseHttpObserver<BaseResp>() {
            @Override
            protected void handleResultOkResp(BaseResp resp) {
                orderDetailBean.setStatus(NeedOrderStatusType.YWC.getType());
                if (mNeedOrderBean != null) {
                    mNeedOrderBean.setStatus(NeedOrderStatusType.YWC.getType());
                    EvenBusUtil.updateNeedOrderListItem(mNeedOrderBean);
                }
                getOrderDetail(mOrderDetail.getNeedsID(), result -> startReceiptAct(result));

            }
        });
    }

    private void print() {
        if (mOrderDetail == null) return;
        if (!mIsLoadSuccess) {
            DialogUtil.show(context, "打印页面未加载成功，是否刷新", (dialog, which) -> {
                if (mNeedOrderBean == null) return;
                loadUrl(mNeedOrderBean.getNeedsId());
            });
        } else {
            try {
                PrintUtil.createWebPrintJob(context, mWebView, result -> {
                    if (result) { //打印成功发送给打印机了，默认表示打印了,改变订单状态
                        EvenBusUtil.updateNeedOrderByPrint();
                    }
                });
            } catch (Exception e) {
                ToastUtil.showToast("设备不支持打印");
            }
        }

    }

    //回执
    private void startReceiptAct(NeedOrderDetailBean needOrderDetailBean) {
        Intent intent = new Intent();
        intent.setClass(context, ReceiptActivity.class);
        intent.putExtra("data", needOrderDetailBean);
        intent.putExtra("data2", mNeedOrderBean);
        context.startActivity(intent);
    }


    private void showOrderBaseInfo(NeedOrderDetailBean orderDetailBean) {
        if (orderDetailBean != null) {
            orderTitleTv.setText(orderDetailBean.getCustomerName());
            orderNumTv.setText("需求编号:  " + orderDetailBean.getNeedsNo());
            createOrderTimeTv.setText("下单时间:  " + orderDetailBean.getCreateTime());
            sendOrderTimeTv.setText("配送时间:  " + orderDetailBean.getDeliveryTime());
            remarkTv.setText("备注: " + orderDetailBean.getRemark());
        }
    }

    private void showImages(NeedOrderDetailBean data) {
        imageLinView.removeAllViews();
        imageLinView.setVisibility(VISIBLE);
        List<NeedOrderChangeBean.ImagesBean> changeimages = data.getChangeImages();
        List<String> images = data.getImages();
        if (changeimages == null && images == null) {
            imageLinView.setVisibility(GONE);
            return;
        }
        if (changeimages != null && !changeimages.isEmpty()) {

            if (changeimages != null && !changeimages.isEmpty()) {
                for (NeedOrderChangeBean.ImagesBean imagesBean : changeimages) {
                    if (imagesBean.getChangeType() != 3) {
                        OrderItemImagView itemImagView = new OrderItemImagView(context);
                        itemImagView.showView(imagesBean.getNewX());
                        imageLinView.addView(itemImagView);
                    }

                }
                for (NeedOrderChangeBean.ImagesBean imagesBean : changeimages) {
                    if (imagesBean.getChangeType() == 3) {
                        OrderItemImagView itemImagView = new OrderItemImagView(context);
                        itemImagView.showView(imagesBean.getOld());
                        itemImagView.showDeleteNtView();
                        imageLinView.addView(itemImagView);
                    }

                }
            }
            return;
        }

        if (images == null) {
            return;
        }
        for (String image : images) {
            OrderItemImagView itemImagView = new OrderItemImagView(context);
            itemImagView.showView(image);
            imageLinView.addView(itemImagView);
        }

    }

    private void showOrderGoodInfo(NeedOrderDetailBean orderDetailBean) {
        myListView.setVisibility(VISIBLE);
        List<String> goods = orderDetailBean.getTexts();
        List<NeedOrderChangeBean.TextsBean> textsBeans = orderDetailBean.getChangeTexts();
        if (goods == null && textsBeans == null) {
            myListView.setVisibility(GONE);
            return;
        }
        if (textsBeans != null && !textsBeans.isEmpty()) {
            myListView.setVisibility(VISIBLE);
            myListView.setAdapter(new CommonAdapter<>(context, orderDetailBean.getChangeTexts(), R.layout.view_order_word_item) {
                @Override
                public void convert(ViewHolder var1, NeedOrderChangeBean.TextsBean data) {
                    TextView textView = var1.getView(R.id.contentOldTv);
                    TextView tagView = var1.getView(R.id.tagView);
                    tagView.setVisibility(VISIBLE);
                    SpannableStringBuilder spannableString = new SpannableStringBuilder();
                    ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(Color.BLACK);
                    ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(Color.RED);
                    int changeType = data.getChangeType();
                    OrderChangeType orderChangeType = OrderChangeType.getType(changeType);
                    String olds = data.getOld();
                    String news = data.getNewX();
                    if (orderChangeType != null) {
                        switch (orderChangeType) {
                            case NOT_CHANGE:
                                tagView.setVisibility(INVISIBLE);
                                textView.setText(data.getOld());
                                return;
                            case UPDATE:
                                StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
                                spannableString.append(olds);
                                spannableString.append("   (改：");
                                spannableString.append(news);
                                spannableString.append(")");

                                spannableString.setSpan(foregroundColorSpan1, 0, olds.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(foregroundColorSpan2, olds.length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(strikethroughSpan, 0, olds.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                textView.setText(spannableString);
                                break;
                            case ADD:
                                spannableString.append(news);
                                String newdata = "   (新增)";
                                spannableString.append(newdata);


                                spannableString.setSpan(foregroundColorSpan1, 0, news.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(foregroundColorSpan2, news.length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableString);

                                return;

                            case DELETE:
                                StrikethroughSpan strikethroughSpan2 = new StrikethroughSpan();
                                spannableString.append(olds);
                                spannableString.append("   (删除");
                                spannableString.append(")");
                                spannableString.setSpan(foregroundColorSpan1, 0, olds.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(foregroundColorSpan2, olds.length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(strikethroughSpan2, 0, olds.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                textView.setText(spannableString);
                                break;
                            default:
                                tagView.setVisibility(VISIBLE);
                                textView.setText(data.getOld());
                                return;
                        }

                    }

                }
            });
        } else {
            myListView.setAdapter(new CommonAdapter<>(context, goods, R.layout.view_order_word_item) {
                @Override
                public void convert(ViewHolder var1, String var2) {
                    var1.setText(R.id.contentOldTv, var2);
                }
            });
        }

    }

    public void destory() {
        if (mOrderMangerFragment != null) {
            mOrderMangerFragment.onDestroy();
        }
        if (mWebView != null) {
            mWebView.destroy();
        }


    }


}
